<?php

namespace App\Listeners;

use App\Events\OrderCompletedEvent;
use App\Models\ProxyUser;
use App\Services\ProxyService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class AddProxyUser implements ShouldQueue
{
    /**
     * 任务被处理的延迟时间（秒）。
     *
     * @var int
     */
    public $delay = 10;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 每次尝试的间隔
     *
     * @var int
     */
    public $backoff = 60;

    public $proxyService;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(ProxyService $proxyService)
    {
        $this->proxyService = $proxyService;
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderCompletedEvent  $event
     * @return void
     */
    public function handle(OrderCompletedEvent $event)
    {
        $orderInfo = $event->orderInfo;
        if ($orderInfo->proxy_type !== 1) {
            return true;
        }
        Log::info('触发AddProxyUser监听器 -> 订单ID：' . $orderInfo->order_nu);

        $user_id = $orderInfo->user_id;
        // 启用proxy主用户
        /*$result = $this->proxyService->enabledProxyUser($user_id);
        if (empty($result)) {
            throw new \Exception('启用账号失败');
        }*/

        // 添加代理子账号
        $result = $this->proxyService->createProxyUser($user_id, '000000');
        if ($result['code'] !== 0) {
            throw new \Exception('添加子账号失败');
        }

        Log::info('AddProxyUser监听器执行完毕 --> 订单ID：' . $orderInfo->order_nu);
    }
}
